<template>
  <div class="coupon-wrapper">
    <div class="coupon-header">
      <h1>我的优惠券</h1>
      <div class="filter-container">
        <el-select
            v-model="selectedType"
            placeholder="请选择类型"
            @change="handleFilter"
            class="category-select"
        >
          <el-option
              v-for="(type, index) in couponTypes"
              :key="index"
              :label="type.label"
              :value="type.value"
          ></el-option>
        </el-select>
        <el-select
            v-model="selectedStatus"
            placeholder="请选择状态"
            @change="handleFilter"
            class="status-select"
        >
          <el-option
              v-for="(status, index) in couponStatus"
              :key="index"
              :label="status.label"
              :value="status.value"
          ></el-option>
        </el-select>
      </div>
    </div>

    <!-- 优惠券列表 -->
    <div class="coupon-container">
      <el-row :gutter="20">
        <el-col
            :xs="24" :sm="12" :md="8" :lg="6"
            v-for="(item, index) in filteredCoupons"
            :key="index"
        >
          <div class="coupon-card" :class="getStatusClass(item.isStatus)">
            <div class="coupon-left">
              <div class="coupon-amount">
                <span>￥</span>
                {{ item.amount }}
              </div>
              <div class="coupon-type">满减券</div>
            </div>
            <div class="coupon-right">
              <div class="coupon-header">
                <span class="coupon-title">{{ item.couponName }}</span>
                <span class="coupon-status-tag" :class="getStatusTagClass(item.isStatus)">
                  {{ getStatusText(item.isStatus) }}
                </span>
              </div>
              <div class="coupon-content">
                <p class="coupon-desc">满{{ item.minAmount }}元可用</p>
                <p class="coupon-time">有效期至：{{ formatDate(item.expiredTime) }}</p>
              </div>
              <div class="coupon-footer">
                <el-button
                    v-if="item.isStatus === 0"
                    type="primary"
                    size="small"
                    @click="useCoupon(item)"
                    class="use-btn"
                >立即使用</el-button>
                <el-button
                    v-else
                    type="info"
                    size="small"
                    disabled
                    class="use-btn"
                >{{ getStatusText(item.isStatus) }}</el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <div v-if="filteredCoupons.length === 0" class="empty-state">
        <img src="@/assets/empty-coupon.png" alt="无优惠券" class="empty-img">
        <p class="empty-text">暂无可用优惠券</p>
        <el-button type="primary" @click="goToGetCoupon">去领券中心</el-button>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="filteredCoupons.length > 0">
      <el-pagination
          background
          :page-count="pageCount"
          v-model:current-page="currentPage"
          :total="total"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { get, post } from "@/plugins/axios";
import { getCookieForObject } from "@/util";
import { copy } from "copy-anything";
import { useRouter } from "vue-router";

const router = useRouter();

// 获取用户ID
const userId = getCookieForObject('user').id;
const params = reactive({
  page: 1,
  limit: 8
});

// 存储优惠券数据
const tableData = reactive({
  records: [],
  pages: 0,
  total: 0
});

// 获取优惠券数据
function getTableData() {
  get('/coupon/getCouponByUid', { userId, pageNo: params.page, pageSize: params.limit }, content => {
    tableData.records = copy(content.records);
    tableData.pages = content.pages;
    tableData.total = content.total;
  });
}

// 初始化获取数据
getTableData();

// 优惠券类型
const couponTypes = [
  { label: '全部', value: '' },
  { label: '立减券', value: '立减' }
];

// 优惠券状态
const couponStatus = [
  { label: '全部', value: '' },
  { label: '未使用', value: 0 },
  { label: '已使用', value: 1 },
  { label: '已过期', value: 2 }
];

const selectedType = ref('立减');
const selectedStatus = ref('');
const currentPage = ref(1);
const pageSize = ref(8);

// 筛选、分页后的数据
const filteredCoupons = computed(() => {
  let tempData = tableData.records;

  // 状态筛选
  if (selectedStatus.value !== '') {
    tempData = tempData.filter(item => item.isStatus === parseInt(selectedStatus.value));
  }
  return tempData;
});

// 总条数
const total = computed(() => tableData.total);
// 总页数
const pageCount = computed(() => Math.ceil(total.value / pageSize.value));

// 筛选事件
const handleFilter = () => {
  currentPage.value = 1;
};

// 分页切换事件
const handlePageChange = (val) => {
  currentPage.value = val;
  params.page = val
  getTableData();
};

// 格式化日期
const formatDate = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return (
      date.getFullYear() + '-' +
      (date.getMonth() + 1).toString().padStart(2, '0') + '-' +
      date.getDate().toString().padStart(2, '0')
  );
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '未使用';
    case 1: return '已使用';
    case 2: return '已过期';
    default: return '未知';
  }
};

// 获取状态标签样式
const getStatusTagClass = (status) => {
  switch (status) {
    case 0: return 'status-tag-unused';
    case 1: return 'status-tag-used';
    case 2: return 'status-tag-expired';
    default: return '';
  }
};

// 获取卡片整体样式
const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'unused-coupon';
    case 1: return 'used-coupon';
    case 2: return 'expired-coupon';
    default: return '';
  }
};

// 立即使用事件
const useCoupon = (item) => {
  if (item.isStatus === 0) {
    ElMessage.success(`跳转到商城，去使用优惠券`);
    router.push({
      path: '/goods',
      query: { categoryId: -1 }
    });
  } else {
    ElMessage.warning('该优惠券无法使用');
  }
};

// 去领券中心
const goToGetCoupon = () => {
  ElMessage.info('跳转到领券中心');
  // 实际项目中替换为领券中心的路由路径
  router.push('/recharge-transfer');
};
</script>

<style lang="scss" scoped>
.coupon-wrapper {
  min-height: calc(100vh - 100px);
  background-color: #fff5e9;
  padding: 20px;
  box-sizing: border-box;

  .coupon-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;

    h1 {
      font-size: 24px;
      color: #303133;
      margin: 0;
    }

    .filter-container {
      display: flex;
      gap: 15px;

      .category-select, .status-select {
        width: 180px;
      }
    }
  }

  .coupon-container {
    min-height: 500px;
  }

  .coupon-card {
    display: flex;
    height: 160px;
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
    }

    &.unused-coupon {
      .coupon-left {
        background: linear-gradient(135deg, #ff9a9e, #fad0c4);
      }
    }

    &.used-coupon {
      opacity: 0.7;
      .coupon-left {
        background: linear-gradient(135deg, #a1c4fd, #c2e9fb);
      }
    }

    &.expired-coupon {
      opacity: 0.7;
      .coupon-left {
        background: linear-gradient(135deg, #d3d3d3, #e0e0e0);
      }
    }

    .coupon-left {
      width: 35%;
      background: #ff6b6b;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
      padding: 15px;
      box-sizing: border-box;

      .coupon-amount {
        font-size: 32px;
        font-weight: bold;
        line-height: 1.2;

        span {
          font-size: 20px;
        }
      }

      .coupon-type {
        font-size: 14px;
        margin-top: 5px;
        background: rgba(255, 255, 255, 0.2);
        padding: 2px 10px;
        border-radius: 20px;
      }
    }

    .coupon-right {
      flex: 1;
      background: white;
      padding: 15px;
      display: flex;
      flex-direction: column;
      position: relative;

      .coupon-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding: 0;
        border: none;

        .coupon-title {
          font-size: 16px;
          font-weight: bold;
          color: #303133;
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .coupon-status-tag {
          font-size: 12px;
          padding: 2px 8px;
          border-radius: 10px;
          margin-left: 10px;

          &.status-tag-unused {
            background: #67c23a;
            color: white;
          }

          &.status-tag-used {
            background: #909399;
            color: white;
          }

          &.status-tag-expired {
            background: #f56c6c;
            color: white;
          }
        }
      }

      .coupon-content {
        flex: 1;

        .coupon-desc {
          font-size: 14px;
          color: #606266;
          margin: 5px 0;
        }

        .coupon-time {
          font-size: 12px;
          color: #909399;
          margin: 5px 0;
        }
      }

      .coupon-footer {
        text-align: right;

        .use-btn {
          padding: 6px 15px;
          border-radius: 16px;
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 50px 0;

    .empty-img {
      width: 200px;
      height: 200px;
      opacity: 0.6;
    }

    .empty-text {
      font-size: 16px;
      color: #909399;
      margin: 15px 0 20px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 20px 0;
  }
}

@media (max-width: 768px) {
  .coupon-wrapper {
    padding: 15px;

    .coupon-header {
      flex-direction: column;
      align-items: flex-start;

      h1 {
        margin-bottom: 15px;
      }

      .filter-container {
        width: 100%;
        flex-direction: column;
        gap: 10px;

        .category-select, .status-select {
          width: 100%;
        }
      }
    }

    .coupon-card {
      .coupon-left {
        width: 30%;

        .coupon-amount {
          font-size: 28px;
        }
      }
    }
  }
}
</style>